# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name： alarm_script
Description :
Author : 'li'
date： 2023/1/3
-------------------------------------------------
Change Activity:
2023/1/3:
-------------------------------------------------
"""
import json
import sys
from urllib.request import urlopen


def _parse_problem(content):
    event_time = content.split('Problem started at ')[1].split(' on ')[0]
    event_date = content.split('Problem started at ')[1].split(' on ')[1].split('\r\n')[0]
    event_time = event_date + ' ' + event_time
    event_name = content.split('Problem name: ')[1].split('\r\n')[0]
    host = content.split('Host: ')[1].split('\r\n')[0]
    level = content.split('Severity: ')[1].split('\r\n')[0]
    if 'Disaster' in level:
        level = 'fatal'
    elif 'High' in level:
        level = 'warning'
    else:
        return None
    # host_name = content.split('Host: ')[1].split('\r\n')[0]
    ret = dict(
        alarm_name=event_name,
        ip=host,
        level=level,
        action='firing',
        alarm_content=event_time,
    )
    return ret
    pass


def _parse_recovery_problem(content):
    event_time = content.split('Problem has been resolved at ')[1].split(' on ')[0]
    event_date = content.split('Problem has been resolved at ')[1].split(' on ')[1].split('\r\n')[0]
    event_time = event_date + ' ' + event_time
    event_name = content.split('Problem name: ')[1].split('\r\n')[0]
    host_name = content.split('Host: ')[1].split('\r\n')[0]
    duration = content.split('Problem duration: ')[1].split('\r\n')[0]
    level = content.split('Severity: ')[1].split('\r\n')[0]
    if 'Disaster' in level:
        level = 'fatal'
    elif 'High' in level:
        level = 'warning'
    else:
        return None
    ret = dict(
        alarm_name=event_name,
        ip=host_name,
        level=level,
        action='resolved',
        alarm_content=f'恢复时间{event_time},持续时间{duration}')
    return ret


def _write_log(content):
    with open('/alert/alarm.log', 'a') as f:
        f.write(content + '\n')


def _main():
    content = sys.argv[1]
    _write_log(content)
    if 'Problem started at' in content:
        json_obj = _parse_problem(content)
    else:
        json_obj = _parse_recovery_problem(content)
    if json_obj is not None:
        json_str = json.dumps(json_obj)
        urlopen("http://127.0.0.1:9527/zabbix_external_alarm", data=json_str.encode('utf8'))


if __name__ == '__main__':
    _main()
